package ntd.util.frame.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.jwt.JWT;
import ntd.util.cache.ComCache;
import ntd.util.cache.FactoryCache;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.data.tool.ToolMysql;

import java.util.Map;

public class ToolLogin {

    private static final String COM_TOKEN = "com-token";
    private static final String PUB_TOKEN = "ntd_fmhb";

    // 当前登录用户 userid
    private static final ThreadLocal<String> THREAD_LOCAL_CURR_ID = new ThreadLocal<>();

    /**
     * 设置当前登录用户数据
     * @param key
     * @param data
     */
    public static void setData(String key, Object data) {
        getCache().map(key, data);
    }

    /**
     * 获取当前登录用户数据
     * @param key
     * @return
     */
    public static Object getData(String key) {
        return getCache().map(key);
    }

    /**
     * 获取完整用户数据包
     * @return
     */
    public static Map<String, Object> data() {
        return getCache().map();
    }

    /**
     * 获取当前登录用户缓存
     * @return
     */
    private static ComCache getCache() {
        return FactoryCache.cache("tool-login-cache-" + getCurrUserId(), 1000 * 60 * 60 * 24);
    }

    /**
     * 获取当前登录用户租户id
     * @return
     */
    public static String getCurrTenantId() {
        String currUserId = getCurrUserId();
        if (StrUtil.startWith(currUserId, "temp_")) {
            // 临时用户处理
            return "temp_tenant_id";
        } else {
            ToolMysql toolMysql = new ToolMysql(FactoryData.dataSource());
            Entity account = toolMysql.findById("account", currUserId);
            return account.getStr("tenant_id");
        }
    }

    /**
     * 获取当前用户id
     * @return
     */
    public static String getCurrUserId() {
        return getUserId(THREAD_LOCAL_CURR_ID.get());
    }

    /**
     * 生成token
     * @param userId
     * @return
     */
    public static String createToken(String userId) {
        return JWT.create()
                .setPayload("userId", userId)
                .setKey(COM_TOKEN.getBytes())
                .sign();
    }

    /**
     * 获取userId根据token
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        if (PUB_TOKEN.equals(token)) {
            return "c56a7423a234d2ae476aac2e101e80ab";
        }
        return StrUtil.toString(JWT.of(token).getPayload("userId"));
    }

    /**
     * 检查用户登录状态 - 直接抛出异常
     */
    public static void checkLogin() {
        if (StrUtil.isBlank(ToolLogin.getCurrUserId())) {
            throw new ComException("请先登录，再进行操作");
        }
    }

    public static void setToken(String token) {
        THREAD_LOCAL_CURR_ID.set(token);
    }
}
